package manage.commons.listeners;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 应用启动的时候如果要做一些动作，写在这里。
 * 
 * @author dongji
 */
public class ApplicationStartupListener implements ServletContextListener {

	protected static final Log log = LogFactory
			.getLog(ApplicationStartupListener.class);

	public void contextDestroyed(ServletContextEvent event) {
		if (log.isDebugEnabled()) {
			log.debug("Servlet context destroyed");
		}
	}

	public void contextInitialized(ServletContextEvent event) {
		if (log.isDebugEnabled()) {
			log.debug("Servlet context initialized");
		}
		ServletContext context = event.getServletContext();
		initEdition(context);
	}

	/**
	 * 设置当前运行版本，引用静态文件时要用到
	 * 
	 * @param context
	 */
	private void initEdition(ServletContext context) {
		String edition = null;
		InputStream in = context
				.getResourceAsStream("/WEB-INF/edition.properties");

		Properties p = new Properties();
		if (in != null) {
			try {
				p.load(in);
				edition = p.getProperty("deploy.edition", null);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		if (StringUtils.isEmpty(edition)) {
			// 如果没有配置文件，则是在开发环境下，版本号为当前时间毫秒数模1000000
			edition = System.currentTimeMillis() % 1000000L + "dev";
		}
		context.setAttribute("edition", edition);
	}
}
